# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : plugin_info_view.py
# Time       ：2023/7/23 22:40
# Author     ：Y-aong
# version    ：python 3.7
# Description：
    插件信息视图
    Plug-in information views
"""
from flask_restx import fields
from sqlalchemy import or_

from apis.plugin import plugin_ns
from apis.plugin.models.plugin_info import PluginInfo
from apis.plugin.schema.plugin_info_schema import PluginInfoSchema
from public.api_utils.api_decorator import handle_api_error
from public.base_export_excel_view import BaseExportExcelView
from public.base_response import MarshalModel
from public.base_view import BaseView, BaseDetailsView

plugin_info = {
    'id': fields.String(description='插件信息ID'),
    'class_name': fields.String(description='插件库类名'),
    'category': fields.String(description='插件库类别'),
    'icon': fields.String(description='插件库图标'),
    'plugin_title': fields.String(description='插件标题'),
    'version': fields.String(description='插件库版本'),
    'method_name': fields.String(description='插件库方法名'),
    'method_desc': fields.String(description='插件库方法描述'),
    'parameters': fields.String(description='插件库方法参数'),
    'return_value': fields.String(description='插件库返回值参数'),
    'title': fields.String(description='节点标题'),
    'node_type': fields.String(description='节点类型'),
    'background': fields.String(description='节点背景'),
}

plugin_info_marshal = MarshalModel('plugin_info', plugin_ns)


class PluginInfoDetailView(BaseDetailsView):
    url = '/info/detail'

    def __init__(self, *args, **kwargs):
        super(PluginInfoDetailView, self).__init__(*args, **kwargs)
        self.table_orm = PluginInfo
        self.table_schema = PluginInfoSchema

    @handle_api_error()
    @plugin_ns.doc(description="获取插件配置详情")
    @plugin_ns.expect(plugin_info_marshal.detail_request())
    @plugin_ns.marshal_with(plugin_info_marshal.detail_response(plugin_info))
    def get(self):
        """获取插件配置详情"""
        return super(PluginInfoDetailView, self).get()


class PluginInfoView(BaseView):
    url = '/info'

    def __init__(self, *args, **kwargs):
        super(PluginInfoView, self).__init__(*args, **kwargs)
        self.table_orm = PluginInfo
        self.table_schema = PluginInfoSchema

    def handle_filter(self):
        self.filter.append(self.table_orm.active == 1)
        for key, val in self.form_data.items():
            if hasattr(self.table_orm, key) and val:
                self.filter.append(getattr(self.table_orm, key) == val)
            elif key == 'keyword' and val:
                self.filter.append(
                    or_(
                        PluginInfo.id == val,
                        PluginInfo.version == val,
                        PluginInfo.method_desc == val
                    )
                )

    @handle_api_error()
    @plugin_ns.doc(description='获取插件列表')
    @plugin_ns.expect(plugin_info_marshal.list_request(plugin_info))
    @plugin_ns.marshal_with(plugin_info_marshal.list_response(plugin_info))
    def get(self):
        """获取插件列表"""
        return super(PluginInfoView, self).get()

    @handle_api_error()
    @plugin_ns.doc(description='创建插件信息')
    @plugin_ns.expect(plugin_info_marshal.create_request(plugin_info))
    @plugin_ns.marshal_with(plugin_info_marshal.create_response())
    def post(self):
        """创建插件信息"""
        return super(PluginInfoView, self).post()

    @handle_api_error()
    @plugin_ns.doc(description='修改插件信息')
    @plugin_ns.expect(plugin_info_marshal.update_request(plugin_info))
    @plugin_ns.marshal_with(plugin_info_marshal.update_response())
    def put(self):
        """修改插件信息"""
        return super(PluginInfoView, self).put()

    @handle_api_error()
    @plugin_ns.doc(description='删除插件信息')
    @plugin_ns.expect(plugin_info_marshal.delete_request())
    @plugin_ns.marshal_with(plugin_info_marshal.delete_response())
    def delete(self):
        """删除插件信息"""
        return super(PluginInfoView, self).delete()


class PluginReportView(BaseExportExcelView):
    url = '/info/export'

    def __init__(self, *args, **kwargs):
        super(PluginReportView, self).__init__(*args, **kwargs)
        from datetime import datetime
        self.file_name = f'task_{datetime.now().strftime("%Y-%m-%d")}'
        self.columns = {
            'id': '序号',
            'class_name': '插件类名',
            'version': '插件版本',
            'method_name': '插件方法',
            'method_desc': '方法描述',
            'parameters': '方法参数',
            'return_value': '方法返回值',
            'title': '节点名称',
            'node_type': '节点类型',
            'creator_name': '创建者',
            'updater_name': '修改者',
            'insert_time': '插入时间',
            'update_time': '更新时间',
        }

    @handle_api_error()
    @plugin_ns.doc('导出插件信息')
    @plugin_ns.expect(plugin_info_marshal.list_request(plugin_info))
    def post(self):
        """导出插件信息"""
        return super(PluginReportView, self).post()
